import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';

export const WebSocketDemo = () => {
  //Public API that will echo messages sent to it back to the client
//   wss://echo.websocket.org
  const [socketUrl, setSocketUrl] = useState('/api/hshsh');
  const [messageHistory, setMessageHistory] = useState ([]);

  const {sendJsonMessage, sendMessage, lastMessage, readyState } = useWebSocket(socketUrl,{
    heartbeat:{
        message: 'ping',
        returnMessage: JSON.stringify({
            data: 'pong'
            
        }),
        timeout: 3100,
        interval: 3000,
    },
    filter: (message) => {
        console.log(5555,message);
        return message.data === 'pong'
    }
  });

  useEffect(() => {
    if (lastMessage !== null) {
        console.log(lastMessage);
        
      setMessageHistory((prev) => prev.concat(lastMessage));
    }
  }, [lastMessage]);

  const handleClickChangeSocketUrl = useCallback(
    () => setSocketUrl('wss://demos.kaazing.com/echo'),
    []
  );

  const handleClickSendMessage = useCallback(() => {
    sendMessage('Hello')
    sendMessage('你好')
    sendMessage(JSON.stringify({
        type: 'test',
        data: 'test data'
      }))

      sendJsonMessage({
        data:111,
        content:"我是文字"
      })

  }, []);

  const connectionStatus = {
    [ReadyState.CONNECTING]: 'Connecting',
    [ReadyState.OPEN]: 'Open',
    [ReadyState.CLOSING]: 'Closing',
    [ReadyState.CLOSED]: 'Closed',
    [ReadyState.UNINSTANTIATED]: 'Uninstantiated',
  }[readyState];

  return (
    <div>
      <button onClick={handleClickChangeSocketUrl}>
        Click Me to change Socket Url
      </button>
      <button
        onClick={handleClickSendMessage}
        disabled={readyState !== ReadyState.OPEN}
      >
        Click Me to send 'Hello'
      </button>
      <span>The WebSocket is currently {connectionStatus}</span>
      {lastMessage ? <span>Last message: {lastMessage.data}</span> : null}
      <ul>
        {messageHistory.map((message, idx) => (
          <span key={idx}>{message ? message.data : null}</span>
        ))}
      </ul>
    </div>
  );
};